<template>
  <div class="roleMgt">
    <div class="btnArea">
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd()" v-has="{code:'sys:role:list',route:$route}">创建</el-button>
      </div>
      <div class="searchArea">
        <!-- <el-input v-model="input" class="searchInput" placeholder="请输入搜索内容" clearable />
        <el-button icon="el-icon-search">搜索</el-button> -->
      </div>
    </div>
    <el-dialog :title="dialogType==='edit'?'编辑角色':'创建角色'" :visible="dialogFormVisible" @close="closeDialog">
      <el-form ref="form" class="railForm" :model="form" :rules="rules">
        <el-form-item label="角色名称:" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" class="formInputW" />
        </el-form-item>
        <el-form-item label="角色描述:" :label-width="formLabelWidth" prop="remark">
          <el-input v-model="form.remark" class="formInputW" autocomplete="off"  type="textarea" :rows="2"/>
        </el-form-item>
        <div>
        </div>
        <el-form-item label="菜单按钮:" :label-width="formLabelWidth">
          <div class="menuWrap">
            <div class="menuLeft">
              <rail-tree ref="railTree" :treeData="treeData" showCheckbox @node-click="nodeClick"
                :checkedKeys="form.menuCheckedIds"></rail-tree>
                <!-- <rail-tree ref="railTree" :treeData="treeData"  @node-click="nodeClick"
               ></rail-tree> -->
            </div>
            <div class="menuRight">
              <span style="color:#909399">当前正在对
                <span style="color:rgb(96, 98, 102)">[ {{selectMenu.meta.title}} ] </span>
                菜单权限进行按钮权限操作</span>
              <span class="menuRightNoData" v-if="selectMenu.meta && (!selectMenu.meta.btnPermission || selectMenu.meta.btnPermission ==0)">暂无数据</span>
              <div v-if="selectMenu.meta && selectMenu.meta.btnPermission" class="menuRightCheck">
               
                <el-checkbox v-for="item in selectMenu.meta.btnPermission" :key="item.code" v-model="item.checked">
                  {{item.name}} 
                  ({{item.code}})
                </el-checkbox>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
    <el-table :data="tableData" style="width: 100%" v-loading = 'loading'>
      <el-table-column prop="id" label="角色ID" />
      <el-table-column prop="name" label="角色名称" />
      <el-table-column prop="remark" label="角色描述" />
      <!-- <el-table-column prop="create_date" label="创建时间" /> -->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <span class="tableEdit" @click="handleEdit(scope)"  v-has="{code:'sys:role:edit',route:$route}">
            <i class="el-icon-edit"></i> 编辑
          </span>
          <span class="tableDel" @click="handleDelete(scope)"  v-has="{code:'sys:role:delete',route:$route}">
            <i class="el-icon-delete"></i>删除
          </span>
        </template>
      </el-table-column>
    </el-table>
    <rail-pagination :page-info="pageInfo" @pagination="getTableData" />
  </div>
</template>

<script>
  import railPagination from '@/components/railPagination/index'
  import utilMenu from '@/utils/formatRoute.js'
  import {
    deepClone
  } from '@/utils'
  import {
    mapGetters
  } from 'vuex'
  import railTree from './components/railTree'
  const defaultForm = {
    id: null,
    name: '',
    remark: '',
    btnCheckedIds: [],
    menuCheckedIds: []
  }

  export default {
    components: {
      railPagination,
      railTree
    },
    computed: {
      // ...mapGetters([
      //   'menus'
      // ])
    },
    data() {
      return {
        submitBtnCheckedKeys:[],
        loading:false,
        selectMenu: {
          meta: {}
        },
        treeData: [],
        dialogFormVisible: false,
        dialogType: 'add',
        formLabelWidth: '120px',
        form: Object.assign({}, defaultForm),
        rules: {
          name: [{
            required: true,
            message: '角色名必填',
            trigger: 'blur'
          }]
        },
        pageInfo: {
          currentPage: 1,
          total: 0,
          pageSize: 10
        },
        input: '',
        tableData: []
      }
    },
    mounted() {
      this.getMenus()
      this.getTableData(this.pageInfo)
    },
    methods: {
      async getMenus(){
        let {data} = await this.$API.post('/api/permission/queryPermissionList')
        let menuData = utilMenu.formatRoute(data)
        this.filterBtnChecked(menuData)
        this.treeData = menuData
      },
      closeDialog() {
        this.form.menuCheckedIds = []
        this.form.btnCheckedIds = []
        this.filterBtnChecked(this.treeData)
        this.$nextTick(() => {
          this.$refs.railTree.$refs.menuTree.setCheckedKeys(this.form.menuCheckedIds)
          this.$refs.railTree.$refs.menuTree.setCurrentKey(0)
          this.selectMenu =  this.$refs.railTree.data[0] //设置右边按钮选项为【菜单】详情
        })
        this.dialogFormVisible = false
      },
      nodeClick(arg) {
        let {
          data,
          node
        } = arg
        this.selectMenu = data
      },
      async getTableData(val) {
        const {
          pageSize,
          currentPage
        } = val
        this.loading = true
        let {data} = await this.$API.post('api/role/queryRolesList',{
          currentPage,
          "name": "",
          pageSize
        })
        this.pageInfo.total = data.total

        this.tableData = data.records
        
        this.loading = false
      },
      getBtnCheckedIds(){
        this.submitBtnCheckedKeys = []
        let innerTreeData = this.$refs.railTree.$refs.menuTree.data //只能refs拿到tree里面的值
        this.recurBtnCheckedIds(innerTreeData)
      },
      recurBtnCheckedIds(data){
        data.forEach(item => {
            if(item.children) this.recurBtnCheckedIds(item.children)
            if(item.meta.btnPermission){
              item.meta.btnPermission.forEach(btn => {
              if(btn.checked) {
                this.submitBtnCheckedKeys.push(btn.id)
              }
            })
            }
        })
      },
      async submitForm(formName) {
        this.$refs[formName].validate(async(valid) => {
          if (valid) {
            let menuCheckedIds = this.$refs.railTree.$refs.menuTree.getCheckedKeys() //获取菜单选中的ids      
            this.getBtnCheckedIds()
            let btnCheckedIds = this.submitBtnCheckedKeys
            
            let perIds = [...menuCheckedIds,...btnCheckedIds]
            const {name,remark,id} = this.form
            let params = {
              remark,
              perIds,
              name
            }
            if(this.dialogType == 'edit'){
              params.id = id
            }
            let {data} = await this.$API.post('api/role/addNewRole',params)
            this.getTableData(this.pageInfo)
            const type = this.dialogType == 'edit' ? '编辑' : '创建'
            this.$message({
              type: 'success',
              message: `${type}成功!`
            })
            this.dialogFormVisible = false
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
        this.dialogFormVisible = false
      },
      filterBtnChecked(data) {
        let checkedArr = this.form.btnCheckedIds
        
        data.forEach((item, key) => {
          if (item.children) {
            this.filterBtnChecked(item.children)
          }
          if (item.meta && item.meta.btnPermission && item.meta.btnPermission.length) {
            
            const btnPermissionArr = item.meta.btnPermission
            btnPermissionArr.forEach((btn, index) => {
              btn.checked = false
              if (checkedArr.includes(btn.id)) {
                btn.checked = true
              }
            })
          }
        })
      },
      filterCheck() {
        this.$nextTick(() => {
          this.$refs.railTree.$refs.menuTree.setCheckedKeys(this.form.menuCheckedIds) //菜单设置勾选项
          this.$refs.railTree.$refs.menuTree.setCurrentKey(0) //设置【菜单】默认选择
          this.selectMenu =  this.$refs.railTree.data[0] //设置右边按钮选项为【菜单】详情
          this.filterBtnChecked(this.treeData) //按钮设置勾选项
        })
        
      },
      handleAdd() {
        this.form = Object.assign({}, defaultForm)
        this.dialogType = 'add'
        this.filterCheck()
        this.dialogFormVisible = true
      },
      async handleEdit(scope) {
        const id = scope.row.id
        let {data} = await this.$API.post('/api/role/queryRolesById',{id})
        this.fitlerCheckedLst(data)//处理表格数据，preLst转换成menuCheckedIds和btnCheckedIds
        this.form = deepClone(data) //从后端拿取数据
        //this.form = deepClone(scope.row)
        this.dialogType = 'edit'
        this.filterCheck()
        this.dialogFormVisible = true
      },
      fitlerCheckedLst(item){
          let menuCheckedIds = []
          let btnCheckedIds = []
          if(item.perList){
            item.perList.forEach(per => {
              if(per.type == 1){
                menuCheckedIds.push(per.id)
              }else if(per.type == 2){
                btnCheckedIds.push(per.id)
              }
            })
          }
          item.menuCheckedIds = menuCheckedIds
          item.btnCheckedIds = btnCheckedIds
      },
      async handleDelete({
        $index,
        row
      }) {
        const id = row.id
        const rolename = row.name
        this.$confirm(`确定删除 [ ${rolename} ] ?`, '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(async () => {
            let {data} = this.$API.post('api/role/deleteRoleById',{id}) 
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.pageInfo.currentPage = 1
            this.getTableData(this.pageInfo)
          })
          .catch(err => {
            console.error(err)
          })
      }
    }
  }

</script>

<style lang="scss" scoped>
  .btnArea {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .searchArea {
    display: flex;
    align-items: center;

    .searchInput {
      margin-right: 10px;
    }
  }

  .tableEdit {
    color: $themeColor;
    margin-right: 5px;
    cursor: pointer;
    font-size: 12px;
  }

  .tableDel {
    color: $themeColor;
    cursor: pointer;
    font-size: 12px;
  }

  .formInputW {
    width: 300px;
  }

  // 菜单选择区域
  .menuWrap {
    display: flex;
    height: 400px;

    .menuLeft {
      padding: 15px;
      flex: 1;
      border: 1px solid rgb(220, 223, 230);
      margin-right: 30px;
      overflow-y: auto;
    }

    .menuRight {
      padding: 10px;
      flex: 1;
      border: 1px solid rgb(220, 223, 230);
      display: flex;
      flex-direction: column;

      .menuRightNoData {
        text-align: center;
        padding: 20px;
        color: #909399;
      }

      .menuRightCheck {
        display: flex;
        flex-direction: column;
      }
    }
  }

</style>
<style scoped>
  .el-form-item__label {
    font-weight: 400;
  }

  .railForm /deep/ .el-form-item.roleSelectWrap.el-select--medium{
    width: 100% !important;
  }
</style>
